package com.company.Lock;

import cn.hutool.core.date.DateUtil;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class LockDemo {
    static Lock lock = new ReentrantLock(); // sync关键字
//    static MyLock lock = new MyLock(); // sync关键字

    public static void main(String args[]) throws InterruptedException {
        for (int i = 0; i < 2; i++) {
            Thread th = new Thread(() -> {
                System.out.println(Thread.currentThread() + "准备抢锁 "+ DateUtil.now());
                lock.lock(); // 抢锁过程，没拿到锁 等待
                try {
                    System.out.println(Thread.currentThread() + "拿到锁" + DateUtil.now());
                    Thread.sleep(3_000L);  // TODO 拿到锁开始干活，模拟耗时3秒
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    lock.unlock(); // 解锁
                }
            });
            th.start();
        }

        Thread.sleep(60000L);
    }

}
